//
//  SearchViewController.m
//  Product_NEWS
//
//  Created by dllo on 16/1/13.
//  Copyright © 2016年 FCH. All rights reserved.
//

#import "SearchViewController.h"
#import "SerachModel.h"
#import "SerachDetailViewController.h"
@interface SearchViewController ()<UISearchControllerDelegate,UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UISearchResultsUpdating>
@property(nonatomic,retain)NSMutableArray *modelArray;
@property(nonatomic,retain)NSMutableArray *searchArray;

@property(nonatomic,retain)UITableView *myTableView;

@property(nonatomic,retain)UISearchController *searchController;

@property(nonatomic,retain)UITableViewCell *cell;

@end

@implementation SearchViewController


-(NSMutableArray *)searchArray
{
    if (!_searchArray) {
        self.searchArray = [NSMutableArray array];
    }
    return [[_searchArray retain]autorelease];
}
-(NSMutableArray *)modelArray
{
    if (!_modelArray) {
        self.modelArray = [NSMutableArray array];
    }
    return [[_modelArray retain]autorelease];
}
- (void)viewDidLoad {
    [super viewDidLoad];

    
    [self initUI];
   
    
}

-(void)initUI
{ self.searchController =[[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater = self;
    //    设置开始搜索时背景显示与否 页面背景阴影效果,一般不要设置.
    self.searchController.dimsBackgroundDuringPresentation = NO;
    //设置点击搜索框时候隐藏导航栏
    self.searchController.hidesNavigationBarDuringPresentation = NO;
    self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
    //    [searchBar sizeToFit]:设置searchBar位置自适应
    [self.searchController.searchBar sizeToFit];
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    [self.view addSubview:self.myTableView];
    [_myTableView release];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    
    self.searchController.delegate =self;
    self.searchController.searchBar.delegate = self;
    self.myTableView.tableHeaderView = self.searchController.searchBar;
    [self.myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
}






#pragma mark --使用AFN进行post请求
//点击键盘搜索按钮实现搜索功能
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self.modelArray removeAllObjects];
    NSString *str = self.searchController.searchBar.text;
    str = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
     NSDictionary *dic= @{@"page":@"1",@"keyword":[NSString stringWithFormat:@"%@", str]};
    NSString *url_string = [NSString stringWithFormat:@"http://admin.tingwen.me/index.php/api/interface/postList?"];
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    
   
    
    
    [manager POST:url_string parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSLog(@"%@",responseObject);
        NSMutableArray *array = [responseObject objectForKey:@"results"];
       
         if (array != nil) {
        
        for (NSDictionary *dic in array) {
            
            SerachModel *model = [[SerachModel alloc]init];
            
            [model setValuesForKeysWithDictionary:dic];
            
            [self.modelArray addObject:model];
          
            [self.searchArray addObject:model.post_title];
            [model release];
        }
         }else{
             self.cell.textLabel.text = @"没有搜索结果";
         }
        [self.myTableView reloadData];//刷新tableview
      
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        
    }];
    
    
}
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    
}


#pragma mark  -- tableDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.modelArray.count) {
        
        return self.modelArray.count;
    }else{
        return 1;
        
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    self.cell =[tableView dequeueReusableCellWithIdentifier:@"cell"];
   
    if (self.modelArray.count) {
        
        NSMutableAttributedString *att = [[NSMutableAttributedString alloc]initWithString:[self.searchArray objectAtIndex:indexPath.row]];
        [att addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[[self.searchArray objectAtIndex:indexPath.row] rangeOfString:[self.searchController.searchBar text]]];
        self.cell.textLabel.numberOfLines = 0;
        
        self.cell.textLabel.attributedText =att;
    }
    return self.cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    SerachModel *model = nil;
    
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        
        NSLog(@"选中搜索列表");
        model = [self.searchArray objectAtIndex:indexPath.row];
        
    }
    else {
        
        NSLog(@"选中所有列表");
        model = [self.modelArray objectAtIndex:indexPath.row];
        
    }
    
    SerachDetailViewController *detailVC = [[SerachDetailViewController alloc] init];
  
    [self.navigationController pushViewController:detailVC animated:YES];
    [detailVC release];
    
    
}

//输入文字就触发的方法
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    
    NSLog(@"输入框中的内容=====%@",searchText);
    [self.searchArray removeAllObjects];
    for (SerachModel *model in self.modelArray) {
        
        //rangeOfString:方法是在movieName中搜索是否包含searchText
        //rangeOfString 前面的参数是要被搜索的字符串，后面的是要搜索的字符
        //NSNotFound 表示请求操作的某个内容没有发现
        if ([model.post_title rangeOfString:searchText].location != NSNotFound) {
            
            [self.searchArray addObject:model];
        }
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
    
}



//UISearchController的移除
//在viewWillDisappear中要将UISearchController移除, 否则切换到下一个View中, 搜索框仍然会有短暂的存在.
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.searchController.active) {
        self.searchController.active = NO;
        [self.searchController.searchBar removeFromSuperview];
    }
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
